import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Stack;

public class BinaryTree {

    static class TreeNode {
        public char val;
        public TreeNode right;
        public TreeNode left;

        public TreeNode(char val) {
            this.val = val;
        }
    }
    public TreeNode createTree() {
        TreeNode A = new TreeNode('A');
        TreeNode B = new TreeNode('B');
        TreeNode C = new TreeNode('C');
        TreeNode D = new TreeNode('D');
        TreeNode E = new TreeNode('E');
        TreeNode F = new TreeNode('F');
        TreeNode G = new TreeNode('G');

        A.left = B;
        A.right = C;
        B.left = D;
        B.right = E;
        C.left = F;
        C.right = G;
        return A;
    }


    //二叉树的创建和遍历
    //输入：abc##de#g##f###
    //输出：c b e g d f a
    //https://www.nowcoder.com/practice/4b91205483694f449f94c179883c1fef?tpId=60&&tqId=29483&rp=1&ru=/activity/oj&qru=/ta/tsing-kaoyan/question-ranking
    public static int i = 0;
    public TreeNode creatTree(String str) {
        TreeNode root = null;

        if (str.charAt(i) != '#') {
            root = new TreeNode(str.charAt(i));
            i++;
            root.left = creatTree(str);
            root.right = creatTree(str);
        } else {
            i++;
        }
        return root;
    }


    //前序遍历
    public void preOrder(TreeNode root) {
        if (root == null) {
            return;
        }
        System.out.print(root.val + " ");
        preOrder(root.left);
        preOrder(root.right);
    }

    //前序遍历非递归实现
    //https://leetcode.cn/problems/binary-tree-preorder-traversal/description/
    public List<Character> preorderTraversal(TreeNode root) {
        List<Character> ret = new LinkedList<>();
        if (root == null) {
            return ret;
        }

        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;

        while(cur != null || !stack.isEmpty()) {

            while(cur != null) {
                ret.add(cur.val);
                stack.push(cur);
                cur = cur.left;
            }

            TreeNode top = stack.pop();
            cur = top.right;
        }
        return ret;
    }

    //中序遍历
    public void inOrder(TreeNode root) {
        if (root == null) {
            return;
        }
        inOrder(root.left);
        System.out.print(root.val + " ");
        inOrder(root.right);
    }

    //中序遍历非递归实现
    //https://leetcode.cn/problems/binary-tree-inorder-traversal/
    public List<Character> inorderTraversal(TreeNode root) {
        List<Character> ret = new LinkedList<>();
        if (root == null) {
            return ret;
        }

        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;

        while(cur != null || !stack.isEmpty()) {

            while(cur != null) {
                stack.push(cur);
                cur = cur.left;
            }

            TreeNode top = stack.pop();
            ret.add(top.val);
            cur = top.right;
        }
        return ret;
    }
    //后序遍历
    public void postOrder(TreeNode root) {
        if (root == null) {
            return;
        }

        postOrder(root.left);
        postOrder(root.right);
        System.out.print(root.val + " ");
    }


    //后序遍历非递归实现
    //https://leetcode.cn/problems/binary-tree-postorder-traversal/
    public List<Character> postorderTraversal(TreeNode root) {
        List<Character> ret = new LinkedList<>();
        if (root == null) {
            return ret;
        }

        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode prev = null;
        while(cur != null || !stack.isEmpty()) {

            while(cur != null) {
                stack.push(cur);
                cur = cur.left;
            }

            TreeNode top = stack.peek();

            if (top.right == null || top.right == prev) {
                ret.add(top.val);
                stack.pop();
                prev = top;
            }else {
                cur = top.right;
            }
        }
        return ret;
    }
    //层序遍历
    public void levelOrder(TreeNode root) {
        if (root == null) {
            return;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while(!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            System.out.print(cur.val + " ");

            if (cur.left != null) {
                queue.offer(cur.left);
            }
            if (cur.right != null) {
                queue.offer(cur.right);
            }
        }
    }

    //返回总结点的个数
    //第一种
    public static int usedSize;//我们用于存放结点个数的
    public int size1(TreeNode root) {
        if (root == null) {
            return 0;
        }

        usedSize++;
        size1(root.left);//遍历左子树
        size1(root.right);//遍历右子树

        return usedSize;
    }
    //第二种
    public int size2(TreeNode root) {
        if (root == null) {
            return 0;
        }

        return size2(root.left) + size2(root.right) + 1;
    }

    //获得叶子结点的个数
    //第一种
    public static int leafSize;
    public int getLeafNodeCount1(TreeNode root) {
        if (root == null) {
            return 0;
        }

        if (root.left == null && root.right == null) {
            leafSize++;
        }

        getLeafNodeCount1(root.left);
        getLeafNodeCount1(root.right);

        return leafSize;
    }
    //第二种
    public int getLeafNodeCount2(TreeNode root) {
        if (root == null) {
            return 0;
        }
        if (root.left == null && root.right == null) {
            return 1;
        }

        return getLeafNodeCount2(root.left) + getLeafNodeCount2(root.right);
    }

    //获得第k层的结点的个数。
    public int getKLevelNodeCount(TreeNode root,int k) {
        if (root == null) {
            return 0;
        }
        if (k == 1) {
            return 1;
        }

        return getKLevelNodeCount(root.left,k-1) + getKLevelNodeCount(root.right,k-1);
    }

    //获取二叉树的高度
    //时间复杂度：O(N)
    //空间复杂度：O(logN)
    public int getHeight(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);

        //谁高谁加一
        return leftHeight > rightHeight ? leftHeight + 1 : rightHeight + 1;
    }

    //检测值为value的元素是否存在
    //时间复杂度：O(N)
    //空间复杂度：O(logN)
    public TreeNode find(TreeNode root,char val) {
        if (root == null) {
            return null;
        }
        //先判断根结点
        if (root.val == val) {
            return root;
        }
        //如果不是就去左子树中寻找
        TreeNode leftNode = find(root.left,val);
        if (leftNode != null) {
            //如果我们在左子树中找到的话，我们在上面根的判断就返回了我们和val相等的结点，
            //在这里我们只需要判断是否为空就可以了，不为空，就是val的这个结点，反之则没有
            return leftNode;
        }
        //去右子树中寻找
        TreeNode rightNode = find(root.right,val);
        if (rightNode != null) {
            //我们这里同上
            return rightNode;
        }

        return null;
    }

    //判断一棵树是不是完全二叉树
    public boolean isCompleteTree(TreeNode root) {
        if (root == null) {
            return true;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while(!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            if (cur != null) {
                queue.offer(cur.left);
                queue.offer(cur.right);
            }else {
                break;
            }
        }

        while(!queue.isEmpty()) {
            TreeNode peek = queue.peek();
            if (peek != null) {
                return false;
            }
            queue.poll();
        }

        return true;
    }

    //判断两个二叉树是否相同、
    //https://leetcode.cn/problems/same-tree/
    public boolean isSameTree(TreeNode p, TreeNode q) {
        //先判断p和q的结构
        if (p != null && q == null || p == null && q != null) {
            //结构出现错误
            return false;
        }

        //可能是因为都为null或者都不为空
        //都为空下：
        if (p == null && q == null) {
            return true;
        }

        //都不为空
        //判断对相应的节点的值是否一样
        if (p.val != q.val) {
            return false;
        }

        //走到这，就是这个节点判断完成，并且是相同的，我们之后去其左子树和右子树检查
        return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
        //我们递归正确返回的是真
    }

    //另一棵树的子树
    //https://leetcode.cn/problems/subtree-of-another-tree/
    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        if (root == null) {
            return false;
        }

        if (isSameTree(root,subRoot)) {
            return true;
        }
        if (isSubtree(root.left,subRoot)) {
            return true;
        }
        if (isSubtree(root.right,subRoot)) {
            return true;
        }

        return false;
    }

    //返转二叉树
    //https://leetcode.cn/problems/invert-binary-tree/description/
    public TreeNode invertTree(TreeNode root) {
        if (root == null) {
            return null;
        }
        //进行当前根的左子树和右子树的替换
        TreeNode cur = root.left;
        root.left = root.right;
        root.right = cur;

        //到根的左子树和右子树去替换
        //这里用遍历
        invertTree(root.left);
        invertTree(root.right);

        return root;
    }

    //对称二叉树
    //https://leetcode.cn/problems/symmetric-tree/
    public boolean isSymmetricChild(TreeNode leftTree,TreeNode rightTree) {
        //结构不一样的情况下
        if (leftTree != null && rightTree == null
                || leftTree == null && rightTree != null) {
            return false;
        }
        //在结构一样的情况下左右子树都等于空
        if (leftTree == null && rightTree == null) {
            return true;
        }
        //在结构一样的情况下左右子树都不等于空
        //我们来判断左值和右值是否相等
        if (leftTree.val != rightTree.val) {
            return false;
        }

        //之后我们来遍历左子树的子树，右子树的右子树，再次判断是否结构相等和值是否相等
        return isSymmetricChild(leftTree.left,rightTree.right) &&
                isSymmetricChild(leftTree.right,rightTree.left);
    }
    public boolean isSymmetric(TreeNode root) {
        if (root == null) {
            return false;
        }

        return isSymmetricChild(root.left,root.right);
    }

    //平衡二叉树
    //时间复杂度:O(N^2)  因为每一个节点都要去求高度，会重复去求高度，所以我们的getHeight就是有重复求的节点高度
    //https://leetcode.cn/problems/balanced-binary-tree/
    public boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }

        int leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);

        //Math.abs是取绝对值
        return Math.abs(leftHeight - rightHeight) < 2
                && isBalanced(root.left)
                && isBalanced(root.right);
    }

    //平衡二叉树
    //时间复杂度:O(N)
    public boolean isBalanced2(TreeNode root) {
        if (root == null) {
            return true;
        }
        //返回-1就是错误的
        return getHeight2(root) >= 0;
    }

    public int getHeight2(TreeNode root) {
        //我们在求高度的时候呢就把这个是否是平衡二叉树的这个问题就给解决了
        if (root == null) {
            return 0;
        }
        int leftHeight = getHeight2(root.left);
        if (leftHeight < 0) {
            //小于0就不走右面了
            return -1;
        }
        int rightHeight = getHeight2(root.right);


        if (rightHeight >= 0 && Math.abs(leftHeight - rightHeight) < 2) {
            //这里返回左树和右树的最大值 + 1
            return Math.max(leftHeight,rightHeight) + 1;
        }else {
            return -1;
        }
    }

    //二叉搜索树和双向链表
    //https://www.nowcoder.com/practice/947f6eb80d944a84850b0538bf0ec3a5?tpId=295&tqId=23253&ru=/exam/oj&qru=/ta/format-top101/question-ranking&sourceUrl=%2Fexam%2Foj
    public TreeNode prev = null;
    public void ConvertChild(TreeNode root) {
        if (root == null) {
            return;
        }
        //中序遍历是对于有序地二叉树的打印是有序的
        ConvertChild(root.left);
        //这里我们左面遍历之后，我们要把二叉树变成双向链表
        root.left = prev;
        if (prev != null) {
            prev.right = root;
        }
        prev = root;
        ConvertChild(root.right);

    }
    public TreeNode Convert(TreeNode pRootOfTree) {
        if (pRootOfTree == null) {
            return null;
        }

        //进行对于二叉树的排序，变成双向链表
        ConvertChild(pRootOfTree);
        //我们找排序完成后的头
        TreeNode head = pRootOfTree;
        while(head.left != null) {
            head = head.left;
        }

        return head;
    }


    //二叉树的层序遍历
    //https://leetcode.cn/problems/binary-tree-level-order-traversal/submissions/564446369/
    public List<List<Character>> levelOrder2(TreeNode root) {
        List<List<Character>> ret = new LinkedList<>();
        if (root == null) {
            return ret;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while(!queue.isEmpty()) {
            int size = queue.size();
            List<Character> lsit = new LinkedList<>();

            while(size != 0) {
                TreeNode cur = queue.poll();
                lsit.add(cur.val);
                if (cur.left != null) {
                    queue.offer(cur.left);
                }
                if (cur.right != null) {
                    queue.offer(cur.right);
                }
                size--;
            }
            ret.add(lsit);
        }
        return ret;
    }

    //二叉树的层序遍历二
    //https://leetcode.cn/problems/binary-tree-level-order-traversal-ii/submissions/565000115/
    public List<List<Character>> levelOrderBottom(TreeNode root) {
        List<List<Character>> ret = new LinkedList<>();
        if (root == null) {
            return ret;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Character> lsit = new LinkedList<>();
            while (size != 0) {
                TreeNode cur = queue.poll();
                lsit.add(cur.val);
                if (cur.left != null) {
                    queue.offer(cur.left);
                }
                if (cur.right != null) {
                    queue.offer(cur.right);
                }
                size--;
            }
            ret.add(lsit);
        }

        List<List<Character>> ret2 = new LinkedList<>();
        for (int i = ret.size() - 1; i >= 0; i--) {
            ret2.add(ret.get(i));
        }
        return ret2;
    }

    //二叉树的最先公共祖先
    //https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) {
            return null;
        }

        //第一种情况
        if (root == p || root == q) {
            return root;
        }

        //找节点 p 和 q
        TreeNode leftTree = lowestCommonAncestor(root.left,p,q);
        TreeNode rightTree = lowestCommonAncestor(root.right,p,q);
        //在判断是否为空
        if (leftTree != null && rightTree != null) {
            return root;
        }else if (leftTree != null) {
            return leftTree;
        }else {
            return rightTree;
        }
    }

    /**
     * 二叉树的最先公共祖先
     * @param root 这个是二叉树
     * @param node 我们要查找的节点
     * @param stack 我们存放节点的栈
     * @return
     */
    public boolean getPath(TreeNode root, TreeNode node, Stack<TreeNode> stack) {
        if (root == null) {
            return false;
        }
        stack.push(root);

        if (root == node) {
            return true;
        }

        boolean ret = getPath(root.left,node,stack);
        if (ret == true) {
            return true;
        }

        ret = getPath(root.right,node,stack);
        if (ret == true) {
            return true;
        }

        stack.pop();
        return false;
    }

    public TreeNode lowestCommonAncestor2(TreeNode root,TreeNode p,TreeNode q) {
        if (root == null) {
            return null;
        }

        //创建队列来存放路径上的节点
        Stack<TreeNode> stack1 = new Stack<>();
        Stack<TreeNode> stack2 = new Stack<>();
        getPath(root,p,stack1);
        getPath(root,q,stack2);

        //求长度看谁长，谁先有它们的长度差
        int size1 = stack1.size();
        int size2 = stack2.size();

        if (size1 > size2) {
            int size = size1 - size2;
            while(size != 0) {
                stack1.pop();
                size--;
            }
        }else {
            int size = size2 - size1;
            while(size != 0) {
                stack2.pop();
                size--;
            }
        }

        while(!stack1.isEmpty() && !stack2.isEmpty()) {

            if (stack1.peek() == stack2.peek()) {
                return stack1.peek();
            }else {
                stack1.pop();
                stack2.pop();
            }
        }

        return null;
    }


    //根据二叉树创建字符串
    //https://leetcode.cn/problems/construct-string-from-binary-tree/description/
    public String tree2str(TreeNode root) {
        if (root == null) {
            return null;
        }

        StringBuilder stringBuilder = new StringBuilder();
        tree2strChild(root,stringBuilder);
        return stringBuilder.toString();
    }

    public void tree2strChild(TreeNode root,StringBuilder stringBuilder){
        if (root == null) {
            return;
        }

        stringBuilder.append(root.val);

        if (root.left != null) {
            stringBuilder.append('(');
            tree2strChild(root.left,stringBuilder);
            stringBuilder.append(')');
        }else {
            if (root.right == null) {
                return;
            }else {
                stringBuilder.append("()");
            }
        }

        if (root.right != null) {
            stringBuilder.append('(');
            tree2strChild(root.right,stringBuilder);
            stringBuilder.append(')');
        }else {
            return;
        }


    }
}
